//
//  PubLishViewController.m
//  TheRoadAD
//
//  Created by baixue on 16/8/9.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "PubLishViewController.h"
#import "BSSquareCell.h"
#import "ZYQAssetPickerController.h"

@interface PubLishViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate>
{
    UIButton             *_addPic;
    NSMutableArray       *_imageArray;
}

@property (weak, nonatomic) IBOutlet UIView *backView;
@property (nonatomic ,strong) UICollectionView *collectionView;

@end
#define  margin  5
#define  cellWH  (Screen_Width - 10*5)/3
static NSString *const ID = @"BSSquareCell";
@implementation PubLishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"精选";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_home_meitu_1"] style:UIBarButtonItemStylePlain target:self action:@selector(backItem)];
//    [self setUpFooterView];
    [self setInterface];
}


-(void)setInterface{
    _imageArray = [NSMutableArray array];
    
    // + pic
    _addPic = [UIButton buttonWithType:UIButtonTypeCustom];
    _addPic.frame = CGRectMake(15, 15, 70, 70);
    [_addPic setImage:[UIImage imageNamed:@"+"] forState:UIControlStateNormal];
    [_addPic addTarget:self action:@selector(addPicEvent) forControlEvents:UIControlEventTouchUpInside];
    [_backView addSubview:_addPic];
    _backView.frame = CGRectMake(15, 50, Screen_Width-15*2, CGRectGetMaxY(_addPic.frame)+20);

}

- (void)addPicEvent
{
    if (_imageArray.count >= 9) {
        NSLog(@"最多只能上传9张图片");
    } else {
        [self selectPictures];
    }
}

// 本地相册选择多张照片
- (void)selectPictures
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 9;
//    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
                              {
                                  if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo])
                                  {
                                      NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                                      
                                      return duration >= 5;
                                  } else {
                                      return YES;
                                  }
                              }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}

// 9宫格图片布局
- (void)nineGrid
{
    for (UIImageView *imgv in _backView.subviews)
    {
        if ([imgv isKindOfClass:[UIImageView class]]) {
            [imgv removeFromSuperview];
        }
    }
    
    CGFloat width = 70;
    CGFloat widthSpace = (Screen_Width - 15*4 - 70*4) / 3.0;
    CGFloat heightSpace = 10;
    
    NSInteger count = _imageArray.count;
    _imageArray.count > 9 ? (count = 9) : (count = _imageArray.count);
    
    for (int i=0; i<count; i++)
    {
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(15+(width+widthSpace)*(i%4), 15, width, width)];
        imgv.image = _imageArray[i];
        imgv.userInteractionEnabled = YES;
        [_backView addSubview:imgv];
        
        UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
        delete.frame = CGRectMake(width-16, 0, 16, 16);
        delete.backgroundColor = [UIColor greenColor];
        [delete addTarget:self action:@selector(deleteEvent:) forControlEvents:UIControlEventTouchUpInside];
        delete.tag = 10+i;
        [imgv addSubview:delete];
        
        if (i == _imageArray.count - 1)
        {
            if (_imageArray.count % 4 == 0) {
                _addPic.frame = CGRectMake(15, CGRectGetMaxY(imgv.frame) + heightSpace, 70, 70);
            } else {
                _addPic.frame = CGRectMake(CGRectGetMaxX(imgv.frame) + widthSpace, CGRectGetMinY(imgv.frame), 70, 70);
            }
            
        }
    }
}

// 删除照片
- (void)deleteEvent:(UIButton *)sender
{
    UIButton *btn = (UIButton *)sender;
    [_imageArray removeObjectAtIndex:btn.tag-10];
    
    [self nineGrid];
    
    if (_imageArray.count == 0)
    {
        _addPic.frame = CGRectMake(15, 15, 70, 70);
    }
}

#pragma mark - ZYQAssetPickerController Delegate

- (void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                   {
                       for (int i=0; i<assets.count; i++)
                       {
                           ALAsset *asset = assets[i];
                           UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
                           [_imageArray addObject:tempImg];
                           
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [self nineGrid];
                           });
                       }
                   });
}





//创建流水布局
-(void)setUpFooterView{
    // 1.创建流水布局
    UICollectionViewFlowLayout *layout = ({
        
        // 1.创建流水布局
        UICollectionViewFlowLayout *layout =  [[UICollectionViewFlowLayout alloc] init];
        
        // 2.设置流水布局属性
        
        // 2.1设置cell尺寸
        layout.itemSize = CGSizeMake(cellWH, cellWH);
        
        // 2.2 设置cell之间间距
        layout.minimumLineSpacing = margin;
        
        layout;
    });
    
    // 2.创建UICollectionView
    UICollectionView *collectionView = ({
        
        // 1.创建UICollectionView
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, Screen_Width, cellWH) collectionViewLayout:layout];
        
        
        
        // 2.设置数据源 -> 要UICollectionView展示数据
        collectionView.dataSource = self;
        collectionView.delegate = self;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        collectionView.showsHorizontalScrollIndicator = NO;
        
        
        // 3. 注册cell
        [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BSSquareCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
        
        // 4.不允许collectionView滚动
        // 取消弹簧效果
        //        collectionView.bounces = NO;
//        collectionView.scrollEnabled = NO;
        collectionView.backgroundColor = [UIColor whiteColor];
        
        
        collectionView;
        
    });
    
    _collectionView = collectionView;
    
    // 3.设置collectionView为tableView的footView
    // 设置tableView的footView,高度由我们自己决定,宽度,位置都是控制不了
    [_backView addSubview:collectionView];
    


}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(0, 10, 0, 0);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    

    BSSquareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
//     获取模型
//     BSSquareItem *item = self.squareList[indexPath.row];
//    
//     cell.item = item;
   
    return cell;
}

//每个item的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}
-(void)backItem {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
     return 9;

    
}

@end
